<?php

namespace App\Http\Controllers\Backend;


use App\Http\Requests\Backend\ImageUploadRequest;
use App\Http\Requests\Company\ImageRequest;
use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Business\Models\Image;
use App\Services\Business\Interfaces\VideoServiceInterface;
use App\Services\Business\Models\MediaCategory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;


class ImageController extends BaseController
{
    public function index(Request $request)
    {

        $keywords = $request->input('keywords');
        $categoryId = (int)$request->input('media_category_id');

        $images = Image::query()
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when($categoryId, function ($query) use ($categoryId) {
                $ids = [$categoryId];
                $childrenIds = MediaCategory::query()
                    ->where('parent_id', $categoryId)
                    ->select(['id'])
                    ->get()
                    ->pluck('id')
                    ->toArray();
                $ids = array_merge($ids, $childrenIds);
                $query->whereIn('category_id', $ids);
            })
            ->orderByDesc('id')
            ->paginate($request->input('size'));

        return $this->successData(compact('images'));
    }


    /**
     * 更新时插入插入图片
     * @param ImageRequest $request
     * @param $id
     * @return JsonResponse
     */
    public  function store(ImageRequest $request, Image $image)
    {

        $image->fill($request->filldata())->save();
        return  $this->successData(compact('image'));

    }



    public function delete($id,ConfigServiceInterface $configService, VideoServiceInterface $videoService)
    {

        $image = Image::query()->where('id', $id)->first();
        $videoService->deleteImage($image->media_id, $configService);
        $image->delete();
        return $this->success();
    }

    public function update(Request $request, $id)
    {

        Image::find($id)->update(['title' => $request->input('title')]);
        return $this->success(__('图片更新成功'));
    }

//    替换文件
    public function replace(ImageUploadRequest $request, $id)
    {
        $file = $request->filldata();
        $prefix = 'editor/' . date("Ymd");
        $data = save_image($file, $prefix);
        // 创建记录
        Image::query()->where('id', $id)->update([
            'title' => $data['name'],
            'media_url' => $data['url'],
            'path' => $data['path'],

        ]);
        return $this->success(__('图片更新成功'));
    }

    public function remove(Request $request)
    {
        $categoryId = $request->input('category_id');
        $ids = $request->input('ids', []);
        Image::query()->whereIn('id', $ids)->update(['category_id' => $categoryId]);
        return $this->success(__('批量移至文件夹成功'));
    }


}
